package pers.zb.cloud.web.upms.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import pers.zb.cloud.web.upms.entity.SysRole;
import pers.zb.cloud.web.upms.entity.SysRoleOperateLog;
import pers.zb.cloud.web.upms.enums.RoleStatus;
import pers.zb.cloud.web.upms.service.RoleService;
import pers.zb.cloud.web.upms.vo.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色服务
 */
@Slf4j
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;


    /**
     * 角色列表页面
     */
    @RequestMapping(value = "/view/list", method = {RequestMethod.GET})
    public String view() {
        return "/sys/role/list";
    }

    /**
     * 分页获取角色列表
     */
    @ResponseBody
    @RequestMapping(value = "/list")
    public Page<SysRole> getRoleList(Page pageParam,SysRole roleParam){
        Map<String,Object> params = new HashMap<>();
        params.put("pageParam",pageParam);
        params.put("roleParam",roleParam);
        Page<SysRole> roleList = roleService.getRoleListForPage(params);
        return roleList;
    }

    /**
     * 进入角色修改页面
     */
    @RequestMapping(value = "/{roleId}", method = {RequestMethod.PUT})
    public ModelAndView edit(@PathVariable("roleId") Long roleId) {
        SysRole sysRole = roleService.getRoleById(roleId);

        ModelAndView modelAndView = new ModelAndView("/sys/role/edit");
        modelAndView.addObject("role",sysRole);
        modelAndView.addObject("status",RoleStatus.values());
        return modelAndView;
    }

    /**
     * 更新、添加角色
     *      type： 1 - 更新   2 - 添加
     */
    @RequestMapping(value = "/{type}", method = {RequestMethod.POST})
    @ResponseBody
    public JsonResult<String> updateOrSave(@PathVariable("type") int type, SysRole sysRole) {
        JsonResult<String> jsonResult = new JsonResult<>();
        try {
            roleService.updateOrSave(type,sysRole);
        } catch (Exception e) {
            log.debug("更新 or 添加角色 - 失败：" + e.getMessage());
            jsonResult.setCode(500);
            jsonResult.setMsg(e.getMessage());
            return jsonResult;
        }
        return jsonResult;
    }

    /**
     * 进入新增角色页面
     */
    @RequestMapping(value = "/view/add", method = {RequestMethod.GET})
    public ModelAndView addRoleVew() {
        ModelAndView modelAndView = new ModelAndView("/sys/role/add");
        modelAndView.addObject("status",RoleStatus.values());
        return modelAndView;
    }


    /**
     * 删除角色
     */
    @RequestMapping(value = "/batch", method = {RequestMethod.POST})
    @ResponseBody
    public JsonResult<String> delete(@RequestParam(value = "roleId") String roleIds) {
        JsonResult<String> jsonResult = new JsonResult<>();
        try {
            String[] roleIdArrString = roleIds.split(",");
            Long roleIdArr[] = (Long[])ConvertUtils.convert(roleIdArrString, Long.class);
            roleService.deleteRole(roleIdArr);
        } catch (Exception e) {
            log.debug("删除角色 - 失败：" + e.getMessage());
            jsonResult.setCode(500);
            jsonResult.setMsg(e.getMessage());
            return jsonResult;
        }
        return jsonResult;
    }


    /**
     * 进入角色详情页面
     *      form : 角色管理页面 - 下方的tab选项卡 - 详情页
     *
     * @param roleId 角色ID
     */
    @RequestMapping(value = "/detail/view", method = {RequestMethod.GET})
    public ModelAndView detail(@RequestParam("roleId") Long roleId) {
        SysRole sysRole = roleService.getRoleById(roleId);

        ModelAndView modelAndView = new ModelAndView("/sys/role/detail");
        modelAndView.addObject("role",sysRole);
        modelAndView.addObject("status",RoleStatus.values());
        return modelAndView;
    }

    /**
     * 分页获取角色操作日志列表
     *      form : 角色管理页面 - 下方的tab选项卡 - 操作日志
     */
    @ResponseBody
    @RequestMapping(value = "/list/operate/log")
    public Page<SysRoleOperateLog> getRoleOperateLogForPage(Page pageParam, SysRoleOperateLog roleOperateLogParam){
        Map<String,Object> params = new HashMap<>();
        params.put("pageParam",pageParam);
        params.put("roleOperateLogParam",roleOperateLogParam);
        Page<SysRoleOperateLog> roleOperateLog = roleService.getRoleOperateLogForPage(params);
        return roleOperateLog;
    }

    @RequestMapping(value = "/permission/list")
    @ResponseBody
    public List<RolePermissionVo> getRolePermissionList(@RequestParam(value = "roleId",required = false) Long roleId) {
        List<RolePermissionVo> rolePermissionVoList = new ArrayList<RolePermissionVo>();
        if(roleId == null){//菜单列表默认不显示数据，只有当点击左侧应用的时候，才会显示对应的应用菜单列表
            return rolePermissionVoList;
        }
        rolePermissionVoList = roleService.getRolePermissionTreeList(roleId);
        return rolePermissionVoList;
    }


    /**
     * 获取角色应用授权集合
     *      前端显示为 tree ， 同时每个节点前面显示 checkedbox 选项框。 已经授权的应用的checkedbox为选中状态，反之是未选中状态
     * @param roleId
     * @return
     */
    @RequestMapping(value = "/client/authorize/list")
    @ResponseBody
    public List<RoleClientAuthorizeVo> getPermissionListById(@RequestParam(value = "roleId",required = false) Long roleId) {
        List<RoleClientAuthorizeVo> roleClientAuthorizeVoList = new ArrayList<RoleClientAuthorizeVo>();
        if(roleId == null){
            return roleClientAuthorizeVoList;
        }
        roleClientAuthorizeVoList = roleService.getRoleClientAuthorizeList(roleId);
        return roleClientAuthorizeVoList;
    }

    /**
     * 为角色设置应用的访问权限
     *
     * @param clientId 应用的client_id的集合，逗号分隔
     */
    @RequestMapping(value = "/batch/client/authorize", method = {RequestMethod.POST})
    @ResponseBody
    public JsonResult<String> roleClientAuthorize(@RequestParam(value = "clientId") String clientId,@RequestParam(value = "roleId") Long roleId) {
        JsonResult<String> jsonResult = new JsonResult<>();
        try {
            String[] clientIdArrString = null;
            if(StringUtils.isNotBlank(clientId)){
                clientIdArrString = clientId.split(",");
            }

            roleService.roleClientAuthorize(roleId,clientIdArrString);
        } catch (Exception e) {
            log.debug("为角色设置应用的访问权限 - 失败：" + e.getMessage());
            jsonResult.setCode(500);
            jsonResult.setMsg(e.getMessage());
            return jsonResult;
        }
        return jsonResult;
    }


    /**
     *  获取角色拥有应用访问权限的应用列表
     *      from : 角色管理 -> 角色权限设置 -> 角色已授权系统
     */
    @RequestMapping(value = "/client/authorize/tree/list")
    @ResponseBody
    public List<ClientVo> getRoleClientAuthorizeListTree(@RequestParam(value = "roleId",required = false) Long roleId) {
        List<ClientVo> clientVoList = new ArrayList<>();
        if(roleId == null){
            return clientVoList;
        }
        clientVoList = roleService.getRoleClientAuthorizeListTree(roleId);
        return clientVoList;
    }

    /**
     * 获取角色在应用中的权限
     *
     * @param clientId 应用的client_id
     * @param roleId 角色ID
     */
    @RequestMapping(value = "/client/permission/list/{permissionId}")
    @ResponseBody
    public List<RoleClientPermissionVo> getRoleClientPermissionList(@RequestParam(value = "clientId",required = false) String clientId,
                                                                    @RequestParam(value = "roleId",required = false) Long roleId,
                                                                    @PathVariable(value = "permissionId",required = false) Long permissionId) {
        List<RoleClientPermissionVo> roleClientPermissionVoList = new ArrayList<RoleClientPermissionVo>();
        if(StringUtils.isBlank(clientId) || roleId == null){//菜单列表默认不显示数据，只有当点击左侧应用的时候，才会显示对应的应用菜单列表
            return roleClientPermissionVoList;
        }
        roleClientPermissionVoList = roleService.getRoleClientPermissionList(roleId,clientId,permissionId);

        /*PropertyFilter profilter = new PropertyFilter(){
            @Override
            public boolean apply(Object object, String checked, Object value) {
                if(checked.equalsIgnoreCase("checked") && value.equals(false)){
                    return false;
                }
                return true;
            }
        };
        String roleClientPermissionListString = JSON.toJSONString(roleClientPermissionVoList, profilter);
        return JSON.parseArray(roleClientPermissionListString);*/
        return roleClientPermissionVoList;
    }


    /**
     * 为角色设置应用的功能操作权限
     */
    @RequestMapping(value = "/batch/client/permission", method = {RequestMethod.POST})
    @ResponseBody
    public JsonResult<String> settingRoleClientPermission(@RequestParam(value = "clientId") String clientId,
                                                   @RequestParam(value = "roleId") Long roleId,
                                                   @RequestParam(value = "permissionId") String permissionId) {
        JsonResult<String> jsonResult = new JsonResult<>();
        try {
            String[] permissionIdArrString = new String[]{};
            if(StringUtils.isNotBlank(permissionId)){
                permissionIdArrString = permissionId.split(",");
            }
            roleService.settingRoleClientPermission(clientId,roleId,(Long[])ConvertUtils.convert(permissionIdArrString,Long.class));
        } catch (Exception e) {
            log.debug("为角色设置应用的功能操作权限 - 失败：" + e.getMessage());
            jsonResult.setCode(500);
            jsonResult.setMsg(e.getMessage());
            return jsonResult;
        }
        return jsonResult;
    }
}
